package com.laxia.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.springframework.mail.MailParseException;
import org.springframework.util.CollectionUtils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
import java.security.Security;
import java.util.*;

/**
 * Created by weishuai on 15/19/24.
 */
@Slf4j
public class SendEmailUtil {
    // 163的邮箱配置
//
//    private static String SENDER_NAME = "dlp_savage@163.com";
//    private static String SENDER_PASSWORD = "qutouba123456";
//    private static String HOST = "smtp.163.com";
//    private static String PORT = "465";
//    private static String FROM_NAME = "趣投吧";

    // qq邮箱配置
    private static String SENDER_NAME = "1412859581@qq.com";
    private static String SENDER_PASSWORD = "sauwpadotdeujgag";
    private static String HOST = "smtp.qq.com";
    //    private static String HOST = "smtp.exmail.qq.com";
    private static String PORT = "465";
    private static String FROM_NAME = "美识系统通知";

    //发送邮件方法
    public static Boolean send(String receiverNames, String emailTitle, String emailContents) {
        try {
            log.info("开始发邮件了,emailTitle:{},receiverNames:{}", emailTitle, receiverNames);
            if (StringUtils.isBlank(receiverNames) || StringUtils.isBlank(emailTitle) || StringUtils.isBlank(emailContents)) {
                return false;
            }
            List<String> receivers = Arrays.asList(StringUtils.split(receiverNames, ";"));
            if (CollectionUtils.isEmpty(receivers)) {
                return true;
            }
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

            //获取系统环境
            Properties props = System.getProperties();
            props.setProperty("mail.smtp.host", HOST);
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.smtp.port", PORT);
            props.setProperty("mail.smtp.socketFactory.port", PORT);
            props.setProperty("mail.smtp.auth", "true");
            Authenticator auth = new MyAuthenticator(SENDER_NAME, SENDER_PASSWORD);
            Session session = Session.getInstance(props, auth);


            // 设置session,和邮件服务器进行通讯。
            MimeMessage message = new MimeMessage(session);
            message.setSubject(emailTitle, "UTF-8"); // 设置邮件主题
            message.setText(emailContents, "UTF-8"); // 设置邮件正文
            message.setHeader(emailTitle, emailTitle); // 设置邮件标题
            message.setSentDate(new Date()); // 设置邮件发送日期
            Address address = new InternetAddress(SENDER_NAME, "后台系统邮件", "UTF-8");
            message.setFrom(address); // 设置邮件发送者的地址

            // 为每个邮件接收者创建一个地址
            for (String r : receivers) {

                try {
                    Address[] tos = new InternetAddress[1];
                    tos[0] = new InternetAddress(r);
                    message.setRecipients(Message.RecipientType.TO, tos);
                    log.info("发送邮件 start,receiverNames:{},emailTitle:{},content:{}", JSON.toJSONString(receiverNames), emailTitle, emailContents);
                    Transport.send(message); // 发送邮件
                    log.info("发送邮件 end,receiverNames:{},emailTitle:{},content:{}", JSON.toJSONString(receiverNames), emailTitle, emailContents);
                } catch (MessagingException e) {
                    log.error("发送单个邮件异常,r:{},emailTitle:{},content:{}", r, emailTitle, emailContents, e);
                }
            }
            return true;
        } catch (Exception e) {
            log.error("没识前台发送邮件异常,receiverNames:{},emailTitle:{},content:{}", JSON.toJSONString(receiverNames), emailTitle, emailContents, e);
        }
        return false;
    }


    /**
     * 带html样式内容的
     *
     * @param receiverNames
     * @param emailTitle
     * @param emailContents
     * @return
     */
    public static Boolean sendWithHtml(String receiverNames, String emailTitle, String emailContents) {
        try {
            if (StringUtils.isBlank(receiverNames) || StringUtils.isBlank(emailTitle) || StringUtils.isBlank(emailContents)) {
                return false;
            }
            String[] receivers = StringUtils.split(receiverNames, ";");
            if (receivers.length == 0) {
                return true;
            }
            //获取系统环境
            final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            Properties props = new Properties();
            props.setProperty("mail.smtp.host", HOST);
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.smtp.port", PORT);
            props.setProperty("mail.smtp.socketFactory.port", PORT);
            props.setProperty("mail.smtp.auth", "true");
            Authenticator auth = new MyAuthenticator(SENDER_NAME, SENDER_PASSWORD);
            Session session = Session.getDefaultInstance(props, auth);
            // 设置session,和邮件服务器进行通讯。
            MimeMessage message = new MimeMessage(session);

            Address address = new InternetAddress(SENDER_NAME, FROM_NAME);
            // 设置邮件发送者的地址
            message.setFrom(address);

            // 为每个邮件接收者创建一个地址
            Address[] tos = new InternetAddress[receivers.length];
            for (int i = 0; i < receivers.length; i++) {
                String s = receivers[i];
                tos[i] = new InternetAddress(s);
                message.addRecipient(Message.RecipientType.TO, tos[i]);

            }
            // 设置邮件主题
            message.setSubject(emailTitle);
            // 设置邮件标题
            message.setHeader(emailTitle, emailTitle);
            // 设置邮件发送日期
            message.setSentDate(new Date());
            Multipart mainPart = new MimeMultipart();
            // 创建一个包含HTML内容的MimeBodyPart
            // 设置HTML内容
            BodyPart html = new MimeBodyPart();
            html.setContent(emailContents, "text/html;charset=utf-8");
            mainPart.addBodyPart(html);
            message.setContent(mainPart);
            Transport.send(message);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) {
        SendEmailUtil.sendWithHtml("544160976@qq.com", "11重置密码5", "测试测试");

    }

    /**
     * Description:  邮件授权类
     */
    public static class MyAuthenticator extends javax.mail.Authenticator {
        private String senderName;
        private String senderPassword;

        public MyAuthenticator(String senderName, String senderPassword) {
            this.senderName = senderName;
            this.senderPassword = senderPassword;
        }

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(senderName, senderPassword);

        }
    }


    public static String parseMailTemplate(Map<String, Object> map, String templateFilePath) {
        String str = "";
        try {
            ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader("/template");
            Configuration cfg = Configuration.defaultConfiguration();
            GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
            Template template = gt.getTemplate(templateFilePath);
            for (String value : map.keySet()) {
                template.binding(value, map.get(value));
            }
            str = template.render();
        } catch (IOException e) {
            log.error("邮件模板解析错误", e);
            throw new MailParseException("邮件模板解析错误");
        }
        return str;
    }
}
